-- forward.lua

-- By Tyrone, on 18/04/07
-- Allows a user to forward their PMs to another user

Forwards = {}
nl = string.format('\n')
_, botname = VH:GetConfig("config", "hub_security")

function VH_OnParsedMsgPM(from, data, to)
	if (Forwards[to] ~= nil) then
		if (UserIsOnline(Forwards[to])) and (from ~= botname) then
			SendPMToUser("--Forwarded from "..to.."-- ".."<"..from.."> "..data, Forwards[to], from)
			SendPMToUser("Your message has been forwarded to "..Forwards[to], from, botname)
			--return 0
		else
			return 1
		end
	end
	return 1
end

function VH_OnParsedMsgChat(from, data)
	if (string.find(data, "^%.gayness")) then
		SendMessageToHub("OMG "..string.upper(from).." JUST PM'D ME ADMITTING THEY WERE HOMOSEXUAL :O :O :O", botname)
		return 0
	elseif (string.find(data, "^%.forward")) or (string.find(data, "^%.fwd")) then
		if (Forwards[from] == nil) then
			_,_,user = string.find(data, ".+%s(.+)")
			if (UserIsOnline(user)) then
				if (Forwards[user] == nil) then
					Forwards[from] = user
					SendMessageToUser("All your Private Messages are now being forwarded to "..user..".  Please ensure you tell them to expect your messages and make sure you turn off your forward when you return.", from, botname)
				else
					SendMessageToUser("You cannot set up a forward to this user since they already have a forward set up.", from, botname)
				end
			else
				SendMessageToUser("The user: "..user.." is not online."..nl.."You can only forward messages to users who are online.", from, botname)
			end
		end
		return 0
	elseif (string.find(data, "^%.unforward")) or (string.find(data, "^%.unfwd")) then
		if (Forwards[from] ~= nil) then
			Forwards[from] = nil
			SendMessageToUser("Your Private Message forward was removed.", from, botname)
		else
			SendMessageToUser("You do not currently have a forward set up.  Use .forward <username> to set up one.", from, botname)
		end
		return 0
	end
	return 1
end

function SendPMToUser(message, to, from)
	result, err = VH:SendDataToUser("$To: "..to.." From: "..from.." $<"..from.."> "..message.."|", to)
	return 1
end

function SendMessageToUser(data, nick, from)
	result, err = VH:SendDataToUser("<"..from.."> "..data.."|", nick)
	return 1
end

function UserIsOnline(nick)
	result, sIP = VH:GetUserIP(nick)
	if (string.len(sIP) < 7) then
		return false
	else
		return true
	end
end

function SendMessageToHub(data, from)
	result, err = VH:SendDataToAll("<"..from.."> "..data.."|",0,10)
	return 1
end